using System;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using Jurassic.Library;

namespace Kiwi.Node.Modules.Builtin
{
    public class Sql: BuiltinModuleObject
    {
        public Sql(IApplication application) : base(application)
        {
        }

        [JSFunction(Name = "query")]
        public object Query(string connectionString, string sql)
        {
            using (var connection = new SqlConnection(connectionString))
            {
                using (var command = connection.CreateCommand())
                {
                    command.CommandText = sql;
                    command.CommandType = CommandType.Text;

                    var result = Application.Engine.Array.Construct();
                    connection.Open();
                    using (var reader = command.ExecuteReader())
                    {
                        var names = Enumerable.Range(0, reader.FieldCount).Select(reader.GetName).ToArray();

                        while (reader.Read())
                        {
                            var row = Application.Engine.Object.Construct();
                            for (var i = 0; i < names.Length; ++i)
                            {
                                var value = reader.GetValue(i);
                                if (DBNull.Value == value)
                                {
                                    value = null;
                                }
                                row[names[i]] = value;
                            }
                            result.Push((object)row);
                        }
                        return result;
                    }
                }
            }
        }
    }
}